<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category WebSocketService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/4  17:07
 * +--------------------------------------------------------+
 */

namespace App\Services;


use App\Models\Stock;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class WebSocketService implements WebSocketHandlerInterface
{
    public function __construct()
    {
    }
    // 连接建立时触发
    public function onOpen(Server $server, Request $request)
    {
        // 在触发 WebSocket 连接建立事件之前，Laravel 应用初始化的生命周期已经结束，你可以在这里获取 Laravel 请求和会话数据
        // 调用 push 方法向客户端推送数据，fd 是客户端连接标识字段
        $data = '连接成功'. date('Y-m-d H:i:s');
        $server->push($request->fd, $data);
    }

    // 收到消息时触发
    public function onMessage(Server $server, Frame $frame)
    {
        // 调用 push 方法向客户端推送数据
        Log::info('WebSocket 连接建立');

        $get_url = config('other.stock_url');
        $stock_list = StockService::getInstance()->getAll(2);
        $data     = Stock::get_stock_real_time($stock_list, $get_url);
        $data_cap = Stock::get_stock_real_time_cap($stock_list, $get_url);
        $list = [];
        foreach ( $data as $key => $vo ) {
            $list[] = array_merge($vo, $data_cap[$key]);
        }

        $list = json_encode($list);

        $server->push($frame->fd, $list);
    }

    // 关闭连接时触发
    public function onClose(Server $server, $fd, $reactorId)
    {
        Log::info('WebSocket 连接关闭');
    }


}
